import router from "@/router/index.js";
import { ref } from "vue";
const headers = {
	"X-Requested-With": "XMLHttpRequest",
	//'Authorization': ''
};
export const baseURL = "https://webman.wyx2013.cn";
export const token = ref("");
export function clearCache() {
	localStorage.removeItem("webman_token");
	localStorage.removeItem("webman-pan-dir");
	localStorage.removeItem("webman-pan-files");
}

const http = window.axios.create({
	baseURL,
	headers,
	responseType: "json",
});

http.interceptors.response.use(
	function (response) {
		// 对响应数据做点什么
		if (response.status === 200) {
			if (response.data.code === 0) {
				return response.data.data;
			} else if (response.data.code === 0) {
				return response.data;
			} else if (response.data.code === 401) {
				localStorage.removeItem("webman_token");
				router.push({ path: "/login" });
				return;
			}
			return Promise.reject(response.data);
		}
	},
	function (error) {
		// 对响应错误做点什么
		return Promise.reject(error);
	}
);

export const checkToken = function (tokenObj) {
	if (!tokenObj) {
		const tokenStr = localStorage.getItem("webman_token");
		if (!tokenStr) {
			return;
		}
		tokenObj = JSON.parse(tokenStr);
	}
	const now = new Date().getTime();
	if (now > tokenObj.expires) {
		localStorage.removeItem("webman_token");
		return;
	}
	token.value = "Bearer " + tokenObj.access_token;
	http.defaults.headers.common["Authorization"] =
		"Bearer " + tokenObj.access_token;
};

window.axios_http = http;
checkToken();
export default http;
